package com.tianji.memory;

import cn.hutool.core.collection.CollUtil;
import com.tianji.common.utils.UserContext;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.messages.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class RedisChatMemory implements ChatMemory {
    @Autowired
    private StringRedisTemplate redisTemplate;
    private static final String KEY_PREFIX = "chatMemory";

    @Override
    public void add(String conversationId, List<Message> messages) {
        if (CollUtil.isEmpty( messages)){
            return;
        }
        String key = getKey(conversationId);
        messages.forEach(message -> redisTemplate.opsForList().rightPush(key,MessageUtil.toJson( message)));
    }

    @Override
    public List<Message> get(String conversationId, int lastN) {
        String key = getKey(conversationId);
        List<String> range = redisTemplate.opsForList().range(key, 0, lastN);
        assert range != null;
        return range.stream().map(MessageUtil::toMessage).toList();
    }

    @Override
    public void clear(String conversationId) {
        String key = getKey(conversationId);
        redisTemplate.delete(key);
    }

    private String getKey(String conversationId) {
        return KEY_PREFIX+":" + conversationId;
    }
}
